package com.stylefeng.guns.modular.analysis.manager;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.github.abel533.echarts.Legend;
import com.github.abel533.echarts.VisualMap;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.*;
import com.github.abel533.echarts.data.LineData;
import com.github.abel533.echarts.data.PieData;
import com.github.abel533.echarts.data.PointData;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Funnel;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.series.Series;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.itemstyle.Normal;
import com.stylefeng.guns.common.annotion.PointType;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.constant.bean.PointTypePojo;
import com.stylefeng.guns.common.persistence.model.ContestRule;
import com.stylefeng.guns.common.persistence.model.EmpPoints;
import com.stylefeng.guns.common.persistence.model.QualityGradeRule;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmpPointsService;
import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * Created by jondai on 2018/1/21.
 * option组装服务类
 */
@Service
public class OptionManager {

    @Autowired
    private AnalysisManager analysisManager;

    @Autowired
    private IEmpPointsService empPointsService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;
    /**
     * 五大类别积分比重
     * @param empCodes
     * @param year
     * @return
     */
    public Option totalTrainPointPie(List<String> empCodes, String year) {
        Option basic = new Option();
        basic.title().text("培训积分比重").subtext("五大类别");
        basic.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");
        basic.legend().data("网络培训", "脱产培训", "个人素质", "竞赛调考", "培训能力");
        basic.toolbox().show(true).feature(Tool.mark, Tool.dataView, Tool.restore, Tool.saveAsImage, new MagicType(Magic.pie, Magic.funnel)
                .option(new MagicType.Option().funnel(
                        new Funnel().x("25%").width("50%").funnelAlign(X.left).max(1548))));

        //设置图片数据以及半径角度
        Pie pie = getTrainPip(empCodes,year).center("50%", "45%").radius("50%");
        pie.label().normal().show(true);
        basic.series(pie);

        return basic;
    }
    /**
     * 获取饼图数据
     * 个人素质包含
     * @param
     * @return
     */
    public Pie getTrainPip(List<String> empCodes, String year) {
        return new Pie().name("培训积分").data(
                new PieData("网络培训",  analysisManager.totalNetWorkPoints(empCodes,year)),
                new PieData("脱产培训", analysisManager.totalFullTimePoints(empCodes,year)),
                new PieData("个人素质", analysisManager.totalQualityPoints(empCodes,year)),
                new PieData("竞赛调考",  analysisManager.totalContestPoints(empCodes,year)),
                new PieData("培训能力",  0.0));
    }

    /**
     * @param empCodes
     * @param year
     * @return
     */
    public Option totalSubTrainPointPie(List<String> empCodes, String year) {
//        Option option = new Option();
//        option.title().text("培训积分比重").subtext("九大类别").x(X.center);
//        option.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");
//        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, Tool.restore, Tool.saveAsImage, new MagicType(Magic.pie, Magic.funnel)
//                .option(new MagicType.Option().funnel(
//                        new Funnel().x("25%").width("50%").funnelAlign(X.left).max(1548))));
//        option.legend().orient(Orient.vertical).right(40).top(80).bottom(20);
//        option.legend().data("网络培训", "脱产培训", "学历提升","职业资格","专业技术资格","执业资格","专家人才", "竞赛调考", "培训能力");
//
//        //设置图片数据以及半径角度
//        Pie pie = new Pie();
//        if(empCodes.size() > 0){
//            pie = getSubTrainPip(empCodes,year).center("50%", "45%").radius("50%");
//        }else{
//            PieData pieData = new PieData("无数据", 0.0);
//            pie = pie.name("培训积分").data(pieData).center("50%", "45%").radius("50%");
//        }
//
//        option.series(pie);

        return null;
    }

    public List<Map<String,Object>> getSubTrainPip(List<String> empCodes, String year) {
//        Map<String,Object> result=new HashMap<>();
//        List<EmpPoints> empPointsList=empPointsService.selectByYearInCode(year,empCodes);

//        List<String> fields=new PointTypePojo().parseOptionKey();
        List<Map<String,Object>> data = new ArrayList<>();
        if(CollectionUtils.isEmpty(empCodes) && StringUtils.isEmpty(year)){
            Map<String,Object> result=new HashMap<>();
            result.put("name","无数据");
            result.put("value","0.0");
            data.add(result);
            return data;
        }


        final CountDownLatch latch = new CountDownLatch(9);
        List<PieData> pieDatas = new ArrayList<>();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","网络培训");
            result.put("value",analysisManager.totalNetWorkPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("网络培训", analysisManager.totalNetWorkPoints(empCodes, year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","脱产培训");
            result.put("value",analysisManager.totalFullTimePoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("脱产培训", analysisManager.totalFullTimePoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","学历提升");
            result.put("value",analysisManager.totalDegreeTrainPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("学历提升", analysisManager.totalDegreeTrainPoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","职业资格");
            result.put("value",analysisManager.totalProqualifyTrainPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("职业资格", analysisManager.totalProqualifyTrainPoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","专业技术资格");
            result.put("value",analysisManager.totalProTechPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("专业技术资格", analysisManager.totalProTechPoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","执业资格");
            result.put("value",analysisManager.totalPracticePointsPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("执业资格", analysisManager.totalPracticePointsPoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","专家人才");
            result.put("value",analysisManager.totalExpertTalentsPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("专家人才",  analysisManager.totalExpertTalentsPoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","竞赛调考");
            result.put("value",analysisManager.totalContestPoints(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("竞赛调考",  analysisManager.totalContestPoints(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        new Thread(() -> {
            Map<String,Object> result=new HashMap<>();
            result.put("name","培训能力");
            result.put("value",analysisManager.totalTrainAbility(empCodes, year));
            data.add(result);
//            PieData pie = new PieData("培训能力",  analysisManager.totalTrainAbility(empCodes,year));
//            pieDatas.add(pie);
            latch.countDown();
        }).start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return data;
//        return new Pie().name("培训积分").data(pieDatas.toArray());
    }

    public Option getBarOption() {
        Option option = new Option();
        option.title().text("某地区蒸发量和降水量").subtext("纯属虚构");
        option.tooltip().trigger(Trigger.axis);
        option.legend("蒸发量", "降水量");
        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar).show(true), Tool.restore, Tool.saveAsImage);
        option.calculable(true);
        option.xAxis(new CategoryAxis().data("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"));
        option.yAxis(new ValueAxis());

        Bar bar = new Bar("蒸发量");
        bar.data(2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3);
        bar.markPoint().data(new PointData().type(MarkType.max).name("最大值"), new PointData().type(MarkType.min).name("最小值"));
        bar.markLine().data(new PointData().type(MarkType.average).name("平均值"));

        Bar bar2 = new Bar("降水量");
        List<Double> list = Arrays.asList(2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3);
        bar2.setData(list);
        bar2.markPoint().data(new PointData("年最高", 182.2).xAxis(7).yAxis(183).symbolSize(18), new PointData("年最低", 2.3).xAxis(11).yAxis(3));
        bar2.markLine().data(new PointData().type(MarkType.average).name("平均值"));

        option.series(bar, bar2);
        return option;
    }


    public List<Map<String,Object>> pointStart(String year, List<String> empCodes) {
//        Map<String,Object> condition = new HashMap<>();
//        if(!StringUtils.isEmpty(year)) {
//            condition.put("year", year);
//        }
        List<EmpPoints> empPointsList=empPointsService.selectByYearInCode(year,empCodes);

        QualityGradeRule qualityGradeRule = new QualityGradeRule();
        qualityGradeRule.setGradeType(Const.TRAIN_START);
        EntityWrapper<QualityGradeRule> wrapper = new EntityWrapper<>();
        wrapper.setEntity(qualityGradeRule);
        wrapper.orderBy("integral");
        List<QualityGradeRule> qualityGradeRules = qualityGradeRuleService.selectList(wrapper);

        int one=0;
        int two=0;
        int three=0;
        int four=0;
        int five=0;
        for (EmpPoints empPoints:empPointsList){
            if(empPoints.getTotalPoint().doubleValue()< qualityGradeRules.get(0).getIntegral()){
                one++;
            }else if(empPoints.getTotalPoint().doubleValue()< qualityGradeRules.get(1).getIntegral()){
                two++;
            }else if(empPoints.getTotalPoint().doubleValue()< qualityGradeRules.get(2).getIntegral()){
                three++;
            }else if(empPoints.getTotalPoint().doubleValue()< qualityGradeRules.get(3).getIntegral()){
                four++;
            }else{
                five++;
            }
        }
//        Option option = new Option();
//        option.title().text("积分星级").subtext("");
//        option.tooltip().trigger(Trigger.axis);
//        option.legend("蒸发量", "降水量");
//        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar).show(true), Tool.restore, Tool.saveAsImage);
//        option.calculable(true);
//        option.xAxis(new CategoryAxis().data("一星", "二星", "三星", "四星", "五星"));
//        option.yAxis(new ValueAxis());
//
//        Bar bar = new Bar("员工数");
//        bar.setBarWidth(100);
//        bar.data(one,two,three,four,five);
//        option.series(bar);
//        Option option = new Option();
//        option.title().text("积分星级").subtext("").x(X.center);
//        option.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");
//        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, Tool.restore, Tool.saveAsImage, new MagicType(Magic.pie, Magic.funnel)
//                .option(new MagicType.Option().funnel(
//                        new Funnel().x("25%").width("50%").funnelAlign(X.left).max(1548))));
//        option.legend().orient(Orient.vertical).right(40).top(80).bottom(20);
//        option.legend().data("一星", "二星", "三星", "四星", "五星");

        //设置图片数据以及半径角度
//        Pie pie = new Pie();
////        if(empCodes.size() > 0){
////            pie = getSubTrainPip(empCodes,year).center("50%", "45%").radius("50%");
////        }else{
//            PieData pieData = new PieData("无数据", 0.0);
//            List<PieData> pieDatas = new ArrayList<>();
//            pieDatas.add(new PieData("一星11", one));
//            pieDatas.add(new PieData("二星", two));
//            pieDatas.add(new PieData("三星", three));
//            pieDatas.add(new PieData("四星", four));
//            pieDatas.add(new PieData("五星", five));
////            new Pie().name("积分星级").data(pieDatas);
//            pie = new Pie().name("积分星级").data(pieDatas).center("50%", "45%").radius("50%");
////        }
//        pie.label().normal().show(true);
//        option.series(pie);
        List<Map<String,Object>> data =new ArrayList<>();
        Map<String,Object> map1=new HashMap<>();
        map1.put("name","一星");
        map1.put("value",one);
        data.add(map1);
        Map<String,Object> map2=new HashMap<>();
        map2.put("name","二星");
        map2.put("value",two);
        data.add(map2);
        Map<String,Object> map3=new HashMap<>();
        map3.put("name","三星");
        map3.put("value",three);
        data.add(map3);
        Map<String,Object> map4=new HashMap<>();
        map4.put("name","四星");
        map4.put("value",four);
        data.add(map4);
        Map<String,Object> map5=new HashMap<>();
        map5.put("name","五星");
        map5.put("value",five);
        data.add(map5);

        return data;
    }

    /**
     * 积分广度统计
     * @param year
     * @return
     */
    public Map<String,Object> pointRange(String year,List<String> empCodes){
        Map<String,Object> result=new HashMap<>();
        List<EmpPoints> empPointsList=empPointsService.selectByYearInCode(year,empCodes);
        List<String> fields=new PointTypePojo().parseOptionKey();
        double[] valueArr=new double[fields.size()];
        for (EmpPoints empPoints:empPointsList){
            List<Double> values=JSON.parseObject(empPoints.getModularPonit(),PointTypePojo.class).parseOptionValue();
            for (int i=0 ;i<valueArr.length;i++){
                valueArr[i]=valueArr[i]+values.get(i);
            }
        }
        List<Map<String,Object>> data =new ArrayList<>();
        for (int i=0;i<fields.size();i++) {
            Map<String,Object> map=new HashMap<>();
            map.put("name",fields.get(i));
            map.put("value",valueArr[i]);
            data.add(map);
        }
        result.put("fields",fields);
        result.put("value",data);
        return result;
    }
}
